<template>
  <div class="app-container">
    <!-- 搜索/筛选 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="企业名称" prop="companyName">
        <el-input v-model="queryParams.companyName" placeholder="输入企业名称" clearable @keyup.enter.native="handleQuery" style="width: 200px;" />
      </el-form-item>
      <el-form-item label="企业类型" prop="companyType">
        <el-select v-model="queryParams.companyTypeId" placeholder="选择企业类型" clearable style="width: 150px;">
          <el-option label="全部" :value="''" />
          <el-option v-for="opt in companyTypeOptions" :key="opt.id" :label="opt.typeName" :value="opt.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="企业标签" prop="tagValCond">
        <el-select v-model="queryParams.tagValCond" placeholder="选择企业标签" clearable style="width: 150px;">
          <!-- <el-option label="全部" :value="''" /> -->
          <el-option v-for="opt in companyTagOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="success" size="mini" @click="handleBatchMessage">群发消息</el-button>
        <el-button type="success" size="mini" @click="handleExport">导出</el-button>
        <el-button type="warning" size="mini" @click="handleViewMsgLog">查看消息记录</el-button>
      </el-form-item>
    </el-form>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="companyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" prop="id" width="80" align="center" />
      <el-table-column label="企业名称" prop="companyName" min-width="200" />
      <el-table-column label="企业类型" prop="companyType" min-width="120" align="center" />
      <el-table-column label="统一社会信用代码" prop="uniscid" min-width="180" />
      <el-table-column label="联络人" prop="contact" min-width="100" align="center" />
      <el-table-column label="联系电话" prop="contactPhone" min-width="130" align="center" />
      <el-table-column label="地址" prop="address" min-width="150">
        <template slot-scope="scope">
          {{ scope.row.address || '暂无' }}
        </template>
      </el-table-column>
      <el-table-column label="联企人员" prop="branchName" min-width="120" align="center">
        <template slot-scope="scope">
          {{ scope.row.branchName || '未设置' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" align="center">
        <template slot-scope="scope">
          <div style="display: flex; align-items: center; justify-content: center; gap: 8px;">
            <el-button type="primary" size="mini" @click="handleViewDetail(scope.row)">详情</el-button>
            <el-dropdown @command="(command) => handleMoreAction(command, scope.row)" trigger="click">
              <el-button size="mini">
                更多<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="edit">编辑</el-dropdown-item>
                <el-dropdown-item command="contact">企业标签</el-dropdown-item>
                <el-dropdown-item command="delete">删除企业</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页（通用组件） -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />

    <!-- 编辑企业信息弹框 -->
    <el-dialog
      title="编辑信息"
      :visible.sync="editDialog.visible"
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="editForm"
        :model="editDialog.form"
        :rules="editDialog.rules"
        label-width="120px"
        v-loading="editDialog.loading"
      >
        <!-- Logo上传 -->
        <el-form-item label="Logo">
          <el-upload
            class="logo-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeLogoUpload"
            :http-request="handleLogoUpload"
          >
            <img v-if="editDialog.form.companyLogoUrl" :src="editDialog.form.companyLogoUrl" class="logo-image" />
            <i v-else class="el-icon-plus logo-uploader-icon"></i>
          </el-upload>
          <div class="upload-tip">建议尺寸: 64*64像素, 只能上传jpg/png文件, 且不超过500kb</div>
        </el-form-item>

        <!-- 企业名 -->
        <el-form-item label="企业名">
          <el-input v-model="editDialog.form.companyName" placeholder="请输入企业名称" />
        </el-form-item>

        <!-- 统一社会信用代码 -->
        <el-form-item label="统一社会信用代码">
          <el-input v-model="editDialog.form.uniscid" placeholder="请输入统一社会信用代码" />
        </el-form-item>

        <!-- 地址 -->
        <el-form-item label="地址" prop="address">
          <el-input v-model="editDialog.form.address" placeholder="请输入地址" />
        </el-form-item>

        <!-- 企业类型 -->
        <el-form-item label="企业类型" prop="companyType">
          <el-select v-model="editDialog.form.companyType" placeholder="请选择企业类型" style="width: 100%">
            <el-option
              v-for="opt in companyTypeOptions"
              :key="opt.value"
              :label="opt.label"
              :value="opt.value"
            />
          </el-select>
        </el-form-item>

        <!-- 联系人 -->
        <el-form-item label="联系人" prop="contact">
          <el-input v-model="editDialog.form.contact" placeholder="请输入联系人" />
        </el-form-item>

        <!-- 联系电话 -->
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="editDialog.form.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>

        <!-- 企业网址 -->
        <el-form-item label="企业网址">
          <el-input v-model="editDialog.form.website" placeholder="请输入企业网址" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleEditSubmit" :loading="editDialog.loading">确定</el-button>
      </div>
    </el-dialog>

    <!-- 企业标签弹框 -->
    <el-dialog
      title="企业标签"
      :visible.sync="tagDialog.visible"
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-table 
        v-loading="tagDialog.loading" 
        :data="tagDialog.tagList" 
        empty-text="暂无数据"
        style="width: 100%"
      >
        <el-table-column prop="name" label="名称" width="120" align="center" />
        <el-table-column prop="currentValue" label="当前值" width="120" align="center">
          <template slot-scope="scope">
            {{ scope.row.currentValue || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="pendingValue" label="修改待审值" width="140" align="center">
          <template slot-scope="scope">
            {{ scope.row.pendingValue || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="auditStatus" label="审核状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag 
              :type="getAuditStatusType(scope.row.auditStatus)" 
              size="mini"
            >
              {{ getAuditStatusText(scope.row.auditStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" min-width="150">
          <template slot-scope="scope">
            {{ scope.row.remarks || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template slot-scope="scope">
            <el-button 
              type="text" 
              size="mini" 
              @click="handleEditTag(scope.row)"
              v-if="!scope.row.auditStatus || scope.row.auditStatus === 2"
            >
              编辑
            </el-button>
            <el-button 
              type="text" 
              size="mini" 
              @click="handleDeleteTag(scope.row)"
              style="color: #f56c6c;"
              v-if="!scope.row.auditStatus || scope.row.auditStatus === 2"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="tagDialog.visible = false">关闭</el-button>
        <el-button type="primary" @click="handleAddTag" v-if="tagDialog.companyId">添加标签</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style scoped>
.logo-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 64px;
  height: 64px;
  display: inline-block;
}

.logo-uploader:hover {
  border-color: #409EFF;
}

.logo-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 64px;
  height: 64px;
  line-height: 64px;
  text-align: center;
}

.logo-image {
  width: 64px;
  height: 64px;
  display: block;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
  line-height: 1.4;
}
</style>

<script>
import { listCompany, companyTypeList, companyTagList, deleteCompanyTagCore } from "@/api/biz/api";

export default {
  name: "CompanyUser",
  data() {
    return {
      loading: false,
      // 选中数组
      ids: [],
      multiple: true,
      showSearch: true,
      total: 0,
      companyList: [],
      queryParams: {
        current: 1,
        size: 10,
        companyName: null,
        companyTypeId: null,
        tagValCond: null
      },
      companyTypeOptions: [],
      companyTagOptions: [],
      // 编辑企业弹框
      editDialog: {
        visible: false,
        loading: false,
        form: {
          id: null,
          companyLogoUrl: '',
          companyName: '',
          uniscid: '',
          address: '',
          companyType: '',
          contact: '',
          contactPhone: '',
          website: ''
        },
        rules: {
          address: [
            { required: true, message: '地址不能为空', trigger: 'blur' }
          ],
          companyType: [
            { required: true, message: '企业类型不能为空', trigger: 'change' }
          ],
          contact: [
            { required: true, message: '联系人不能为空', trigger: 'blur' }
          ],
          contactPhone: [
            { required: true, message: '联系电话不能为空', trigger: 'blur' }
          ]
        }
      },
      // 企业标签弹框
      tagDialog: {
        visible: false,
        loading: false,
        companyId: null,
        companyName: '',
        tagList: []
      }
    };
  },
  created() {
    this.fetchCompanyTypeList();
    this.getList(); 
  },
  methods: {
    // 列表数据
    getList() {
      this.loading = true;
      
      // 处理查询参数，确保tagValCond为空字符串时设置为null
      const params = { ...this.queryParams };
      if (params.tagValCond === '' || params.tagValCond === undefined) {
        params.tagValCond = null;
      }
      
      listCompany(params).then(({ data }) => {
        this.companyList = data.records || [];
        this.total = data.total || 0;
        this.loading = false;
      }).catch(() => { this.loading = false; });
    },
    // 获取企业类型列表
    fetchCompanyTypeList() {
      
      companyTypeList()
        .then(({ data }) => {
          this.companyTypeOptions = data;
        })
        .catch((error) => {
          console.error('获取企业类型列表失败:', error);
        });
    },
    handleQuery() {
      this.queryParams.current = 1;
      this.getList();
    },
    resetQuery() {
      this.queryParams = { current: 1, size: 10, companyName: null, companyTypeId: null, tagValCond: null };
      this.getList();
    },
    handleSelectionChange(selection) {
      this.ids = selection;
      this.multiple = !selection.length;
    },
    handleBatchMessage() {
      this.$modal.msg('TODO: 群发消息');
    },
    handleExport() {
      this.$modal.msg('TODO: 导出功能');
    },
    handleViewMsgLog() {
      this.$modal.msg('TODO: 消息记录');
    },
    handleViewDetail(row) {
      console.log(row);
      // 跳转到企业详情页面（使用路径参数）
      this.$router.push({
        path: `/mp/companyuser/detail/${row.id}`
      });
    },
    handleMoreAction(command, row) {
      switch(command) {
        case 'edit':
          this.openEditDialog(row);
          break;
        case 'delete':
          this.$modal.confirm('确认删除此企业，删除企业的同时，会删除企业绑定的微信号，同时解绑联企人员的绑定？').then(() => {
            this.handleDeleteCompany(row);
          }).catch(() => {});
          break;
        case 'contact':
          this.openTagDialog(row);
          break;
      }
    },
    // 打开编辑弹框
    openEditDialog(row) {
      this.editDialog.visible = true;
      this.editDialog.form = {
        id: row.id,
        companyLogoUrl: row.companyLogoUrl || row.logo || '',
        companyName: row.companyName || '',
        uniscid: row.uniscid || '',
        address: row.address || '',
        companyType: row.companyType || '',
        contact: row.contact || '',
        contactPhone: row.contactPhone || '',
        website: row.website || ''
      };
    },
    // 提交编辑
    handleEditSubmit() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.editDialog.loading = true;
          // 这里调用更新企业的API
          // updateCompany(this.editDialog.form).then(() => {
          //   this.$modal.msgSuccess('更新成功');
          //   this.editDialog.visible = false;
          //   this.getList();
          // }).catch(() => {
          //   this.editDialog.loading = false;
          // });
          
          // 模拟API调用
          setTimeout(() => {
            this.$modal.msgSuccess('更新成功');
            this.editDialog.visible = false;
            this.editDialog.loading = false;
            this.getList();
          }, 1000);
        }
      });
    },
    // Logo上传前验证
    beforeLogoUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt500K = file.size / 1024 < 500;

      if (!isJPG) {
        this.$modal.msgError('上传Logo只能是 JPG/PNG 格式!');
      }
      if (!isLt500K) {
        this.$modal.msgError('上传Logo大小不能超过 500KB!');
      }
      return isJPG && isLt500K;
    },
    // 处理Logo上传
    handleLogoUpload(options) {
      const file = options.file;
      const reader = new FileReader();
      reader.onload = (e) => {
        this.editDialog.form.companyLogoUrl = e.target.result;
      };
      reader.readAsDataURL(file);
    },
    // 打开企业标签弹框
    openTagDialog(row) {
      this.tagDialog.visible = true;
      this.tagDialog.companyId = row.id;
      this.tagDialog.companyName = row.companyName;
      this.tagDialog.tagList = [];
      this.fetchCompanyTagList(row.id);
    },
    // 获取企业标签列表
    fetchCompanyTagList(companyId) {
      this.tagDialog.loading = true;
      companyTagList(companyId)
        .then(({ data }) => {
          this.tagDialog.tagList = data || [];
          this.tagDialog.loading = false;
        })
        .catch(() => {
          this.tagDialog.loading = false;
          this.$modal.msgError('获取企业标签失败');
        });
    },
    // 获取审核状态类型
    getAuditStatusType(status) {
      switch(status) {
        case 1: return 'success'; // 审核通过
        case 2: return 'warning'; // 审核不通过
        case 3: return 'info';    // 待审核
        default: return 'info';   // 无状态
      }
    },
    // 获取审核状态文本
    getAuditStatusText(status) {
      switch(status) {
        case 1: return '通过';
        case 2: return '不通过';
        case 3: return '待审核';
        default: return '无';
      }
    },
    // 添加标签
    handleAddTag() {
      this.$modal.msg('TODO: 添加标签功能');
    },
    // 编辑标签
    handleEditTag(row) {
      this.$modal.msg(`编辑标签: ${row.name}`);
    },
    // 删除标签
    handleDeleteTag(row) {
      this.$modal.confirm(`确认删除标签 ${row.name}？`).then(() => {
        this.$modal.msgSuccess('删除成功');
        this.fetchCompanyTagList(this.tagDialog.companyId);
      }).catch(() => {});
    },
    // 删除企业
    handleDeleteCompany(row) {
      // 调用deleteCompanyTagCore接口删除企业
      deleteCompanyTagCore({ companyId: row.id })
        .then(() => {
          this.$modal.msgSuccess('删除成功');
          this.getList();
        })
        .catch(() => {
          this.$modal.msgError('删除失败');
        });
    }
  }
};
</script>
